//
//  OAuthViewController.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/3/31.
//  Copyright © 2017年 HLB. All rights reserved.
//
//这个界面加载一个登入的界面  加载一个网页
import UIKit

class OAuthViewController: UIViewController {
    
    let WB_App_Key = "2517351816"
    let WB_App_Secret = "acd52dcbfb9bccabb646315d5e8d2de5"
    let WB_redirect_uri	 = "http://www.520it.com"
    
    //把控制器的View替换成WebView;
    override func loadView() {
        super.loadView()
        view = webView;
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //0 设置导航栏
        navigationItem.title = "郭为勇微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(close(btu:)))
        //1.获取未授权的requestToken
        //1.1首先凭借一个地址
        //利用UIWebView的特性来加载授权登入界面 (获取未授权的登入界面)
        let path = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
        let url = NSURL(string: path)
        let request = NSURLRequest(url: url! as URL)//转换成NSURL类型
        webView.loadRequest(request as URLRequest)//转换成URLRequest请求
    }
    func close(btu: UIBarButtonItem) -> Void {
        dismiss(animated: true, completion: nil)
    }
//MARK: -- 懒加载一个UIWebView;
    private lazy var webView: UIWebView = {
        
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
}
//MARK: -- UIWebViewDelegate
extension OAuthViewController: UIWebViewDelegate {
    
    ///返回true是正常加载其下面的界面   false是不加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /*
            1.点击登入 加载授权登入界面地址:https://api.weibo.com/oauth2/authorize?client_id=2517351816&redirect_uri=http://www.520it.com
            2.跳转到授权界面的地址: https://api.weibo.com/oauth2/authorize
         
            3.点击授权按钮要跳转到地址:
            https://api.weibo.com/oauth2/authorize#
            https://api.weibo.com/oauth2/authorize
            授权成功
            http://www.520it.com/?code=911fb30a099e9020ba64005749951431
         
            4.点击取消授权的地址:
            https://api.weibo.com/oauth2/authorize#
            https://api.weibo.com/oauth2/authorize
            取消授权
            http://www.520it.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
         */
        //取得url的绝对字符串
        let urlString = request.url?.absoluteString
        //1.先判断是不是授权界面
        //如果地址不是一 WB_redirect_uri 开头的就不是授权界面
        if !urlString!.hasPrefix(WB_redirect_uri) {
            return true
        }
        //2.在判断是授权还是取消授权  取到request的code字段
        let queryString = request.url?.query //得到url?后面的数据
        let codestr = "code="
        if queryString!.hasPrefix(codestr) {
            //取得code
            let code = queryString?.substring(from: codestr.endIndex)
            loadAccessToken(code: code!)
        }else{
            dismiss(animated: true, completion: nil)
        }
        
        return false
    }
    
    func loadAccessToken(code: String) -> Void {
        //1.得到请求地址
        let path = "oauth2/access_token"
        //2.初始化参数
        let prarmDic = ["client_id":WB_App_Key,"client_secret":WB_App_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_redirect_uri]
        //3.加载数据得到access_token
        NetworkTools.shareNetworkTools().post(path, parameters: prarmDic, progress: { (Progress) in
            //print("加载access_token",Progress)
        }, success: { (_, json) in
            /*
             同一个用户对同一个应用授权多次access_token是一样的
             每个access_token都是有期限风险的
                打印json:
             {
             "access_token" = "2.00bw3EvBeMY3kC705e51c8580UkBcw";
             "expires_in" = 157679999;
             "remind_in" = 157679999;
             uid = 1759425497;
             }
             */
            let account = UserAccess(dic: json as! [String : AnyObject])
            //保存信息
            //account.saveAccount()
            //请求个人信息
            account.loadUserInfo(finished: { (userInfo, error) in
                if userInfo != nil{
                    userInfo!.saveAccount()
                    //发送一个通知
                    NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: GWYSwitchRootController), object: false)
                }
                SVProgressHUD.showInfo(withStatus: "网络不给力")
            })
            print("加载access_token",json ?? 99)
        }) { (_, error) in
            print("加载access_token",error)
        }
    }
    
    /// UIWebView开始加载的时候
    ///
    /// - Parameter webView: <#webView description#>
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show(withStatus: "正在加载...")
    }
    /// UIWebView加载完成的时候 
    ///
    /// - Parameter webView: <#webView description#>
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
        }
}

















